var collected = [];
// collected = getAllImages(); // auto collect
// console.log('This is content script.', collected.length);


chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.type == 'reload') {
    chrome.storage.sync.get({
      minHeight: 350,
      minWidth: 350
    }, function (opt) {
      collected = getAllImages(opt.minHeight, opt.minWidth);
      sendResponse({ result: 'ok' });
    });

  }

});

function getAllImages(minHeight, minWidth) {
  var allImages = document.querySelectorAll('img');

  var collected = [];
  for (var i in allImages) {
    var o = allImages[i];
    if (o.width > minWidth && o.height > minHeight) {
      var src = o.getAttribute('src');
      if (o.hasAttribute('init_src')) {
        src = o.getAttribute('init_src');
      }
      if (o.hasAttribute('real_src')) { // 新浪博客
        src = o.getAttribute('real_src');
      }
      if (o.hasAttribute('data-src')) { // 微信公众号
        src = o.getAttribute('data-src');
      }
      if (src.substr(0, 2) == '//') {
        src = 'https:' + src;
      }
      collected.push(src);
    }
  }
  console.log('Get all images on current page.', collected);
  chrome.runtime.sendMessage({ imgCount: collected.length, imgData: collected });
  return collected;
}